-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
59 lines (51 loc) · 1.54 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <vector>
#include <limits>
using namespace std;
const int INF = 1e9; // A large number to represent "infinity"
void floydWarshall(vector<vector<int>> &dist, int V) {
// Use each vertex as an intermediate point.
for (int k = 0; k < V; k++) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][k] != INF && dist[k][j] != INF &&
dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
}
int main() {
int V, E;
cout << "Enter the number of vertices: ";
cin >> V;
cout << "Enter the number of edges: ";
cin >> E;
// Initialize the graph as a V x V matrix.
vector<vector<int>> dist(V, vector<int>(V, INF));
for (int i = 0; i < V; i++) {
dist[i][i] = 0;
}
cout << "Enter each edge in the format: u v weight\n";
for (int i = 0; i < E; i++) {
int u, v, w;
cin >> u >> v >> w;
// Assuming 0-indexed vertices.
dist[u][v] = w;
// For directed graph, comment out the following line.
// dist[v][u] = w;
}
floydWarshall(dist, V);
cout << "\nShortest distances between every pair of vertices:\n";
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
cout << "INF ";
else
cout << dist[i][j] << " ";
}
cout << endl;
}
return 0;
}